package com.ls;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 1 文件传输
 */
public class FileUtils {

    public static void main(String[] args) {
        try {
            transportFile("E:\\s\\A.txt", "E:\\t\\w.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void transportFile(String src, String desc) throws Exception {
        transportFile(new File(src), new File(desc), 5);
    }

    /**
     * 支持断点续传的文件传输
     *
     * @param src  原文件
     * @param desc 目标文件
     */
    public static void transportFile(File src, File desc) throws Exception {
        transportFile(src, desc, 5);
    }


    /**
     * 支持断点续传的文件传输
     *
     * @param src       原文件
     * @param desc      目标文件
     * @param threadNum 开启的线程数
     */
    public static void transportFile(File src, File desc, int threadNum) throws Exception {


        //分成n份,math.ceil向上取整 5.1 = 6.0
        int part = (int) Math.ceil(src.length() / threadNum);


        List<Thread> list = new ArrayList<>();

        //断点续传
        final Map<Integer, Integer> map = new ConcurrentHashMap<>();

        String logName = desc.getCanonicalPath() + ".log";
        File logFile = new File(logName);
        String[] $data = null;

        if (logFile.exists()) {
            //读取记录文件数据
            BufferedReader reader = new BufferedReader(new FileReader(logFile));
            String data = reader.readLine();
            $data = data.split(",");
            reader.close();
        }

        final String[] _data = $data;
        for (int i = 0; i < threadNum; i++) {
            final int k = i;
            Thread thread = new Thread(() -> {
                RandomAccessFile log = null;
                try {
                    RandomAccessFile in = new RandomAccessFile(src, "r");
                    RandomAccessFile out = new RandomAccessFile(desc, "rw");
                    //断点续传,用于记录完成量
                    log = new RandomAccessFile(logName, "rw");

                    //从指定位置读
                    in.seek(_data == null ? k * part : Integer.parseInt(_data[k]));
                    out.seek(_data == null ? k * part : Integer.parseInt(_data[k]));

                    byte[] bytes = new byte[8];

                    //len 每次读到的字节; plen 本线程读到的字节数
                    int len = -1, plen = 0;
                    while (true) {
                        len = in.read(bytes);
                        if (len == -1) {
                            break;
                        }
                        plen += len;
                        //记录线程已经读取的字节索引位置
                        map.put(k, plen + (_data == null ? k * part : Integer.parseInt(_data[k])));
                        out.write(bytes, 0, len);
                        //将map中的数据,进行写入
                        log.seek(0);
                        StringJoiner joiner = new StringJoiner(",");
                        map.forEach((key, val) -> joiner.add(String.valueOf(val)));
                        log.write(joiner.toString().getBytes(StandardCharsets.UTF_8));
                        if (plen + (_data == null ? k * part : Integer.parseInt(_data[k])) >= (k + 1) * part) {
                            break;
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (log != null) {
                        try {
                            log.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
            list.add(thread);
        }


        for (Thread thread : list) {
            thread.join();//将线程加入,并阻塞主线程
        }
        //删除记录文件
        new File(logName).delete();


    }
}

